use godot::prelude::*;

pub struct NodePool<T: Inherits<Node>, const SIZE: usize> {
    nodes: Vec<Gd<T>>,
}

impl<T: Inherits<Node>, const N: usize> NodePool<T, N> {
    pub fn obtain(&mut self, prefab: &Option<Gd<PackedScene>>) -> Gd<T> {
        if let Some(node) = self.nodes.pop() {
            node
        } else {
            prefab.as_ref().unwrap().instantiate_as()
        }
    }

    pub fn free(&mut self, node: Gd<T>) {
        if let Some(mut parent) = node.clone().upcast::<Node>().get_parent() {
            parent.remove_child(&node);
        }

        if self.nodes.len() < N {
            self.nodes.push(node);
        } else {
            node.upcast().queue_free();
        }
    }
}

impl<T: Inherits<Node>, const N: usize> Default for NodePool<T, N> {
    fn default() -> Self {
        Self {
            nodes: Vec::with_capacity(N),
        }
    }
}
